package com.jianganming.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo {

    public static void main(String[] args)throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        InetSocketAddress address = new InetSocketAddress(9999);

        serverSocketChannel.socket().bind(address);

        ByteBuffer byteBuffer = ByteBuffer.allocate(128);

        SocketChannel socketChannel = serverSocketChannel.accept();

        while (true){
            //将数据读到缓冲区
            socketChannel.read(byteBuffer);
            //获取数据的最后位置
            int position = byteBuffer.position();
            //打印数据
            if(position != -1){
                System.out.println(new String(byteBuffer.array(), 0,position));
            }
            //将缓冲区的数组指向0位置
            byteBuffer.flip();
            //清除缓冲区的数据
            byteBuffer.clear();

        }

    }
}
